package com.htgd.gardenexpo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.*;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.IGeConLeisureDataDeckService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htgd.gardenexpo.vo.MileageDurationTrackVO;
import com.htgd.gardenexpo.vo.MyLeisureSportsList;
import com.htgd.gardenexpo.vo.MyTaskDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import static com.htgd.gardenexpo.utils.CalculationUtils.*;
import static com.htgd.gardenexpo.utils.CommonUtils.*;
import static com.htgd.gardenexpo.utils.CommonUtils.formatTrack;
import static com.htgd.gardenexpo.utils.SportsUtils.calculateCalories;
import static com.htgd.gardenexpo.utils.TimeUtils.formatSecondsToTime;
import static com.htgd.gardenexpo.utils.TimeUtils.getTimeRemaining;

/**
 * <p>
 * 挑战甲板数据 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-03
 */
@Service
public class GeConLeisureDataDeckServiceImpl extends ServiceImpl<GeConLeisureDataDeckMapper, GeConLeisureDataDeck> implements IGeConLeisureDataDeckService {

    @Autowired
    private GeConLeisureDataDeckMapper geConLeisureDataDeckMapper;

    @Autowired
    private GeConLeisureSportsMapper geConLeisureSportsMapper;

    @Autowired
    private GeConChallengeSportsMapper geConChallengeSportsMapper;

    @Autowired
    private GeConChallengeSportsTaskMapper geConChallengeSportsTaskMapper;

    @Autowired
    private WxUserDao wxUserDao;


    @Autowired
    private GeConSportsMaxMapper geConSportsMaxMapper;

    @Autowired
    private GeConLeisureDataDeckTaskMapper geConLeisureDataDeckTaskMapper;

    @Override
    public CommonResult add(GeConLeisureDataDeck geConLeisureDataDeck) {
        //新建任务
        GeConLeisureDataDeckTask geConLeisureDataDeckTask = geConLeisureDataDeckTaskMapper.selectById(geConLeisureDataDeck.getTaskId());
        if(geConLeisureDataDeckTask==null){
            GeConLeisureDataDeckTask geConLeisureDataDeckTask1 = new GeConLeisureDataDeckTask();
            geConLeisureDataDeckTask1.setDeckId(geConLeisureDataDeck.getDeckId());
            geConLeisureDataDeckTask1.setId(geConLeisureDataDeck.getTaskId());
            geConLeisureDataDeckTask1.setStatus("1");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(geConLeisureDataDeck.getBeginTime(), formatter);
            geConLeisureDataDeckTask1.setBeginTime(dateTime);
            geConLeisureDataDeckTaskMapper.insert(geConLeisureDataDeckTask1);
        }
        //卡路里
        WxUser wxUser = wxUserDao.getByDeckId(geConLeisureDataDeck.getDeckId());
        double calorie = 0d;
        if(wxUser!=null){
            if(wxUser.getWeight()!=null) {
                calorie = calculateCalories(geConLeisureDataDeck.getMileage(), wxUser.getWeight());
            }else {
                calorie = calculateCalories(geConLeisureDataDeck.getMileage(),70);
            }
        }else {
            calorie = calculateCalories(geConLeisureDataDeck.getMileage(),70);
        }
        //插入数据
        geConLeisureDataDeck.setCalorie(String.valueOf(calorie));
        geConLeisureDataDeckMapper.insert(geConLeisureDataDeck);

        //最大
        String openId = wxUserDao.getOpenId(geConLeisureDataDeck.getDeckId());
        if(openId!=null){
            GeConSportsMax geConSportsMax = geConSportsMaxMapper.selectOne(new LambdaQueryWrapper<GeConSportsMax>().eq(GeConSportsMax::getOpenId, openId));
            if(geConSportsMax!=null){
                String maxMileage = compareAndReturnLarger(geConSportsMax.getMaxMileage(), String.valueOf(geConLeisureDataDeck.getMileage()));
                String maxDuration = compareAndReturnLarger(geConSportsMax.getMaxDuration(), String.valueOf(geConLeisureDataDeck.getDuration()));
                String maxCalorie = compareAndReturnLarger(geConSportsMax.getMaxCalorie(), String.valueOf(calorie));
                geConSportsMaxMapper.update(
                        new GeConSportsMax(),  // 实体类实例（通常为空）
                        new LambdaUpdateWrapper<GeConSportsMax>()
                                .eq(GeConSportsMax::getOpenId, openId)  // 设置更新条件：openId 匹配
                                .set(GeConSportsMax::getMaxMileage, maxMileage)  // 设置需要更新的字段值
                                .set(GeConSportsMax::getMaxDuration, maxDuration)  // 更新最大时长
                                .set(GeConSportsMax::getMaxCalorie, maxCalorie)  // 更新最大卡路里
                );
            }
        }
        return CommonResult.success("新增成功");
    }

    @Override
    public CommonResult getMyList(String openId, Integer pageNum, Integer pageSize) {
        String deckId = wxUserDao.getDeckId(openId);

        PageHelper.startPage(pageNum,pageSize);
        List<MyLeisureSportsList> myLeisureSportsLists = geConLeisureSportsMapper.getMyList(openId);

        for (MyLeisureSportsList myLeisureSportsList : myLeisureSportsLists) {
            if(deckId!=null){
                Map<String,Object> completeDate = geConLeisureSportsMapper.getCompleteData(deckId,myLeisureSportsList.getId());
                Map<String,Object> completeDate2 = geConChallengeSportsTaskMapper.getCompleteData(openId,myLeisureSportsList.getId());
                if("1".equals(myLeisureSportsList.getRule())){ //时长
                    //完成
                    BigDecimal duration = (BigDecimal) completeDate.get("duration");
                    BigDecimal duration2 = (BigDecimal) completeDate2.get("duration");
                    BigDecimal duration3 = duration.add(duration2);
                    String percentage = getPercentage(String.valueOf(duration3), myLeisureSportsList.getTarget());
                    myLeisureSportsList.setComplete(percentage);
                    myLeisureSportsList.setCompleteData(String.valueOf(duration3));
                    //剩余
                    String subtraction = getSubtraction2(String.valueOf(duration3), myLeisureSportsList.getTarget());
                    myLeisureSportsList.setRemain(subtraction);
                }else{
                    //完成
                    Double mileage = (Double) completeDate.get("mileage");
                    Double mileage2 = (Double) completeDate2.get("mileage");
                    Double mileage3 = mileage+ mileage2;
                    String percentage = getPercentage2(String.valueOf(mileage3), myLeisureSportsList.getTarget());
                    myLeisureSportsList.setComplete(percentage);
                    myLeisureSportsList.setCompleteData(String.valueOf(mileage3));
                    //剩余
                    String subtraction = getSubtraction(String.valueOf(mileage), myLeisureSportsList.getTarget());
                    myLeisureSportsList.setRemain(subtraction+"公里");
                }
            }else {
                myLeisureSportsList.setComplete("0");
                if("1".equals(myLeisureSportsList.getRule())){ //时长
                    myLeisureSportsList.setRemain("00:00");
                }else {
                    myLeisureSportsList.setRemain("0"+"公里");
                }
            }

            //倒计时
            String timeRemaining = getTimeRemaining(myLeisureSportsList.getEndTime());
            myLeisureSportsList.setCountdown(timeRemaining);
        }
        PageInfo<MyLeisureSportsList> list  = new PageInfo<>(myLeisureSportsLists);
        return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
    }

    @Override
    public CommonResult updateStatus(String taskId) {
        if(taskId==null){
            return CommonResult.error("缺少任务id");
        }
        boolean exists = lambdaQuery().eq(GeConLeisureDataDeck::getTaskId, taskId).exists();
        if(!exists){
            return CommonResult.error("任务id不存在");
        }

        lambdaUpdate().eq(GeConLeisureDataDeck::getTaskId,taskId)
                .set(GeConLeisureDataDeck::getStatus,"2")
                .update();
        return CommonResult.success("更新成功");
    }

    @Override
    public CommonResult getTaskDetails(String taskId) {
        //基础数据
        MyTaskDetails myTaskDetails = geConLeisureDataDeckMapper.getTaskDetails(taskId);
        MileageDurationTrackVO dataByTaskId = geConLeisureDataDeckMapper.getDataByTaskId(taskId);
        myTaskDetails.setMileage(dataByTaskId.getMileage());
        myTaskDetails.setDuration(String.valueOf(dataByTaskId.getDuration()));
        myTaskDetails.setCalorie(String.valueOf(dataByTaskId.getCalorie()));
        myTaskDetails.setTrack(dataByTaskId.getTrack());
        //运动时间
        String sportsTime = formatTimeRange(myTaskDetails.getBeginTime(), myTaskDetails.getEndTime());
        myTaskDetails.setSportsTime(sportsTime);
        //时长
        String duration = formatSecondsToTime(Long.parseLong(myTaskDetails.getDuration()));
        myTaskDetails.setDuration2(duration);
        //配速
        String speed = getSpeed(Long.parseLong(myTaskDetails.getDuration()), Double.parseDouble(myTaskDetails.getMileage()));
        myTaskDetails.setSpeed(speed);
        //轨迹
        String mergeTrack = mergeTrack(dataByTaskId.getTrack());
        String[] formatTrack = formatTrack(mergeTrack);
        myTaskDetails.setTrack2(formatTrack);
        //用户信息
        GeConLeisureDataDeckTask geConLeisureDataDeckTask = geConLeisureDataDeckTaskMapper.selectById(taskId);
        WxUser wxUser = wxUserDao.getByDeckId(geConLeisureDataDeckTask.getDeckId());
        myTaskDetails.setUserName(wxUser.getName());
        myTaskDetails.setUrl(wxUser.getUrl());
        return CommonResult.success("查询成功",myTaskDetails);
    }
}
